package com.uziot.bucket.file.web;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className FileUploadApplication
 * @date 2019/8/8 13:49
 * @description
 */

@Slf4j
@Controller
public class FileUploadController {

    @PostMapping(value = "/upload")
    public @ResponseBody
    Object upload(HttpServletRequest request, MultipartFile file) {
        this.handlerFile(request, file);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "恭喜，文件上传处理完成！");
        map.put("data", "");
        return map;
    }


    @PostMapping(value = "/files")
    public @ResponseBody
    Object filesUpload(HttpServletRequest request, SimpleUser user) {

        List<MultipartFile> fileList = ((MultipartHttpServletRequest) request).getFiles("file");
        String parameter = request.getParameter("user");
        SimpleUser simpleUser = JSON.parseObject(parameter, SimpleUser.class);
        System.out.println(simpleUser);
        for (MultipartFile f : fileList) {
            this.handlerFile(request, f);
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "恭喜，文件上传处理完成！");
        map.put("data", simpleUser);
        return map;
    }

    private void handlerFile(HttpServletRequest request, MultipartFile multipartFile) {
        String localPath = "D:\\files\\";
        // 获得文件名
        String fileName = multipartFile.getOriginalFilename();
        System.out.println(fileName);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            String filePath = localPath + fileName;
            File file = new File(filePath);
            if (!file.exists()) {
                boolean b = file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(filePath);
            // 缓冲区读文件
            byte[] b = new byte[1024];
            while (inputStream.read(b) != -1) {
                // 未读取到结尾
                fileOutputStream.write(b);
            }
            // 释放资源
            fileOutputStream.close();
            inputStream.close();
            log.info("文件保存完成！");
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

}

@Data
class SimpleUser {
    String userName;
    String userMobile;
}